/*
 * CheckManagement.fx
 * Author： Yu Min-ting
 * Created on 2009-7-14, 14:52:30
 */

package com.sjtu.fx.admin;

import com.sjtu.fx.tools.*;
import com.sjtu.fx.tools.SwingTable.*;

import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;

import javafx.scene.control.Label;

import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;

import org.json.JSONArray;


import javafx.stage.Alert;
import java.lang.System;

import javafx.ext.swing.SwingComboBox;
import javafx.ext.swing.SwingComboBoxItem;
import javafx.scene.control.TextBox;

public class CheckIn{
    public var bookName:String;
    public var userName:String;
    public var libraryName:String;
}

public class CheckOut{
    public var bookName:String;
    public var userName:String;
    public var checkInDate:String;
    public var returnDate:String;
}

public class CheckManagement extends CustomNode {

    var panel:Panel;
    var checkIn:CheckIn[] = bind checkIn with inverse;
    var checkOut:CheckOut[] = bind checkOut with inverse;
     public var cScore:Number;
    public var selectionOut:Integer;
    public var selectionIn: Integer;
    var bookLibraryIdList:Integer[] ;
    var returnbookLibraryInfoId:Integer[];
     var selection:String on replace{
         if(selection == "Others"){
             scoreText.disable = false;
         }else scoreText.disable = true;

     }
    var inTable:SwingTable = SwingTable{
        columns: [
                    TableColumn {
                        text: "Book Name"
                    },
                    TableColumn {
                        text: "User Name"
                    },
                    TableColumn {
                        text: "Library Name"
                    },
                ]
        rows: bind for (u in checkIn)
                    TableRow{
                        cells:[
                            TableCell {
                                text:bind u.bookName
                            },
                            TableCell {
                                text:bind u.userName
                            },
                            TableCell {
                                text:bind u.libraryName
                            },
                        ]
                    }
        selection: bind selectionIn with inverse

    }

      var score = Label {
             text: "borrow date :"
             font: Font {size:10 name: "Verdana"}
             textFill: Color.rgb(11,51,60)
         }
     var scoreTextBox = SwingComboBox {
            text: bind selection with inverse
            items: [
                SwingComboBoxItem {
                    text: "0"
                    selected: true
                }SwingComboBoxItem {
                    text: "1"
                }SwingComboBoxItem {
                    text: "2"
                }SwingComboBoxItem {
                    text: "3"
                }SwingComboBoxItem {
                    text: "4"
                }SwingComboBoxItem {
                    text: "5"
                }SwingComboBoxItem {
                    text: "6"
                }SwingComboBoxItem {
                    text: "7"
                }SwingComboBoxItem {
                    text: "8"
                }SwingComboBoxItem {
                    text: "9"
                }SwingComboBoxItem {
                    text: "10"
                }SwingComboBoxItem {
                    text: "Others"
                }

            ]
        }
    var scoreText = TextBox {
            disable:true
            promptText:"Input Integer here!"
            columns:15
        }


    var accept = Button {
            text: "Accept"
            action: function() {
                if(selectionIn>=0){
                    System.out.println("bookLibraryIdList:{bookLibraryIdList}");
                    if(scoreText.disable != true){
                        CheckBorrowBook(bookLibraryIdList.get(selectionOut) as Integer,Integer.parseInt(scoreText.text) ,1);
                    }else{
                        CheckBorrowBook(bookLibraryIdList.get(selectionOut) as Integer,Integer.parseInt(selection) ,1);
                    }
                    delete checkIn[selectionIn];
                }
            }
        }
     var reject = Button {
             text: "Reject"
             action: function() {
                 if(selectionIn>=0){
                     if(scoreText.disable != true){
                        CheckBorrowBook(bookLibraryIdList.get(selectionOut) as Integer,Integer.parseInt(scoreText.text) ,2);
                    }else{
                        CheckBorrowBook(bookLibraryIdList.get(selectionOut) as Integer,Integer.parseInt(selection) ,2);
                    }
                    delete checkIn[selectionIn];
                }
             }
         }

     var outTable:SwingTable = SwingTable{
        visible:false
        columns: [
                    TableColumn {
                        text: "Book Name"
                    },
                    TableColumn {
                        text: "User Name"
                    },
                    TableColumn {
                        text: "Check in Date"
                    },
                    TableColumn {
                        text: "Promised Return Date"
                    }
                ]
        rows: bind for (u in checkOut)
                    TableRow{
                        cells:[
                            TableCell {
                                text:bind u.bookName
                            },
                            TableCell {
                                text:bind u.userName
                            },
                            TableCell {
                                text: bind u.checkInDate
                            },
                            TableCell {
                                text: bind u.returnDate
                            }
                        ]
                    }
        selection: bind selectionOut with inverse

    }


    var receive = Button {
            visible:false
            text: "Received"
            action: function() {
                if(selectionOut>=0){
                    // to do
                    System.out.println("returnbookLibraryInfoId:{returnbookLibraryInfoId}");
                    checkReturnBook(returnbookLibraryInfoId[selectionOut],4);
                    delete checkOut[selectionOut];
                }
            }
        }
     var deny = Button {
             visible:false
             text: "Denied"
             action: function() {
                 if(selectionOut>=0){
                    checkReturnBook(returnbookLibraryInfoId[selectionOut],5);

                    delete checkOut[selectionOut];
                }
             }
         }

    var refresh = Button {
            visible:false
            text: "Refresh"
            action: function() {
                getReturnList();
            }
        }

        var refreshin = Button {

            text: "Refresh"
            action: function() {
                getBorrowList();
            }
        }
    
 var inManage: Rectangle = Rectangle{
        width:100 height:22
        x:15 y:5
        fill:Color.rgb(200,225,230)
            onMouseEntered: function( e: MouseEvent ):Void {
                inManage.fill = Color.rgb(152, 190, 198)
        }
            onMouseExited: function(e:MouseEvent) {
                inManage.fill = Color.rgb(200,225,230)
        }
            onMouseClicked: function( e: MouseEvent ):Void {
                inTable.visible = true;
                accept.visible = true;
                reject.visible = true;
                score.visible = true;
                scoreTextBox.visible = true;
                scoreText.visible = true;
                outTable.visible = false;
                receive.visible = false;
                deny.visible = false;
                refresh.visible = false;
                refreshin.visible = true;
                // to do

        }
    }
    var inText = Text {
        font: Font {size:14 name: "Verdana Bold"}
        fill: Color.rgb(11,51,60)
        content: "   Check In  "
        x:15 y:20
    };
    var outManage: Rectangle = Rectangle{
        width:100 height:20
        x:119 y:5
        fill:Color.rgb(200,225,230)
            onMouseEntered: function( e: MouseEvent ):Void {
                outManage.fill = Color.rgb(152, 190, 198)
        }
            onMouseExited: function(e:MouseEvent) {
                outManage.fill = Color.rgb(200,225,230)
        }
            onMouseClicked: function( e: MouseEvent ):Void {
                inTable.visible = false;
                accept.visible = false;
                reject.visible = false;
                score.visible = false;
                scoreTextBox.visible = false;
                scoreText.visible = false;
                outTable.visible = true;
                receive.visible = true;
                deny.visible = true;
                refresh.visible = true;
                refreshin.visible = false;
        }
    }
     var outText = Text {
        font: Font {size:14 name: "Verdana Bold"}
        fill: Color.rgb(11,51,60)
        content: "Check Out "
        x:125 y:20

    };

    var alert = UIAlert {
         translateX:75
         translateY:200
         title:"ERROR"
         content:"Please input entire information"
         width:280
         height:120
         visible:false
         opacity:0.9
     }
    override protected function create() : Node {
        getBorrowList();
        getReturnList();
        Group{
            content:[
                 panel = Panel {
                    width:    430
                    height:   550
                    title:    "   Check In   |  Check Out  Management"
                    translateX: 0
                    translateY: 0
                },
                inManage, inText,
                outManage,outText,
                VBox{
                    spacing: 25
                    translateX:32 translateY: 60
                    content:[
                        inTable,
                        HBox{
                             spacing:50
                             content:[score,scoreTextBox,scoreText]
                         },
                        HBox{
                            spacing:50
                            content:[accept, reject,refreshin]
                        }
                    ]

                },
                VBox{
                    spacing: 25
                    translateX:32 translateY: 60
                    content:[
                        outTable,
                        HBox{
                            spacing:50
                            content:[receive,deny,refresh]
                        }
                    ]

                },alert


            ]
        }
     }

    function getBorrowList(){
        HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/BorrowBookList"
       onOutput: function(os:OutputStream) {
             try {
                os.write("1".getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
        try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
       //         System.out.println(result);
                json = new JSONObject(result);
                var borrowList:JSONArray = json.getJSONArray("borrowList");
                var i:Integer = 0;
                while(i<borrowList.length()){
                    var borrowBookInfo:String[] = borrowList.get(i).toString().split("#");
                    checkIn[i] = CheckIn{
                        bookName:borrowBookInfo[1]
                        userName:borrowBookInfo[0]
                        libraryName:borrowBookInfo[2]
                        };
                        System.out.println("borrowBookInfo[3]{borrowBookInfo[3]}");
                        bookLibraryIdList[i] = Integer.parseInt(borrowBookInfo[3].toString());
                    i++;
                }
            } finally {
                is.close();
            }
        }
    }.start();
    }
    
    function getReturnList(){
        HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/ReturnBookList"
       onOutput: function(os:OutputStream) {
             try {
                os.write("1".getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
        try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
       //         System.out.println(result);
                json = new JSONObject(result);
                var returnList:JSONArray = json.getJSONArray("returnList");

                var i:Integer = 0;
                while(i<returnList.length()){
                    var returnBookInfo:String[] = returnList.get(i).toString().split("#");
                    checkOut[i] = CheckOut{
                        bookName:returnBookInfo[1]
                        userName:returnBookInfo[0]
                        checkInDate:returnBookInfo[3]
                        returnDate:returnBookInfo[4]
                        };
                    i++;
                    returnbookLibraryInfoId[i] = Integer.parseInt(returnBookInfo[2]);
                }
            } finally {
                is.close();
            }
        }
    }.start();
    }

    function CheckBorrowBook(bookLibraryId:Integer,borrowDate:Integer,status:Integer){
        HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/CheckBorrowBook"
       onOutput: function(os:OutputStream) {
            try {
                var json:JSONObject = JSONObject{};
                json.put("status",status);
                json.put("bookLibraryId", bookLibraryId);
                json.put("borrowDate",borrowDate);
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var result:String = data.readLine();
                alert.title = "Result";
                alert.content = result;
                alert.visible = true;
                //Alert.inform(result);
            } finally {
                is.close();
            }
        }
    }.start();

    }

    function checkReturnBook(userBookInfoId:Integer, status:Integer){
        HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/CheckReturnBook"
       onOutput: function(os:OutputStream) {
            try {
                var json:JSONObject = JSONObject{};
                json.put("status",status);
                json.put("userBookInfoId", userBookInfoId);
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var result:String = data.readLine();
                alert.title = "Result";
                alert.content = result;
                alert.visible = true;
                //Alert.inform(result);
            } finally {
                is.close();
            }
        }
    }.start();
    }

}
